const momentService = require('../service/moment.service')

class MomentController {
  // 添加动态
  async create(ctx, next) {
    const {content} = ctx.request.body;
    const userId = ctx.user.id;
    try {
      const result = await momentService.create(content, userId)
      ctx.success({
        msg: '添加成功'
      })
    } catch (error) {
      console.log(error.message)
      return
    }    
  }

  // 更新动态
  async update(ctx, next) {
    const {content} = ctx.request.body
    const {momentId} = ctx.params;
    try {
      const result = await momentService.update(content, momentId)
      if(result) {
        ctx.success({
          msg: '修改成功'
        })
      }
    } catch (error) {
      console.log(error.message)
      return 
    }
  }

  // 删除动态
  async remove(ctx, next) {
    const id = ctx.params.momentId
    const result = await momentService.remove(id)
    if(result) {
      ctx.success({
        msg: '删除成功'
      })
    } 
  }

  // 获取动态列表
  async list(ctx, next) {
    const {offset, limit} = ctx.query;
    const result = await momentService.list(offset, limit)
    ctx.success({
      data: result
    })
  }

  // 获取用户的动态列表
  async listByUser(ctx, next) {
    const {userId} = ctx.params
    const {offset, limit} = ctx.query
    try {
      const result = await momentService.listByUser(userId, offset, limit)
    ctx.success({
      data: result
    })
    } catch (error) {
      console.log(error.message)
    }
  }

  // 获取动态详情
  async detail(ctx, next) {
    const {momentId} = ctx.params
    try {
      const result = await momentService.getMomentById(momentId)
      if(result) {
        ctx.success({
          data: result
        })
      } else {
        ctx.fail({
          msg: '获取失败'
        })
      }
    } catch (error) {
      console.log(error.message)      
      return
    }
  }
}

module.exports = new MomentController()